package cn.tedu._05mvcboot02.Controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.AddUserDTO;
import cn.tedu._05mvcboot02.pojo.dto.UserListVo;
import cn.tedu._05mvcboot02.pojo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping(value = "/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "注册功能")
    @PostMapping(value = "insert")
    @ApiImplicitParam(name = "adduserDTO", value = "用户注册信息", required = true, dataType = "AddUserDTO")
    public JsonResult insert(AddUserDTO addUserDTO) {
        log.debug("{}", addUserDTO);
        User user = new User();
        BeanUtils.copyProperties(addUserDTO, user);
        user.setCreated(new Date());
        userMapper.InsertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation(value = "查询功能")
    @GetMapping(value = "userList")
    public JsonResult selectUserList() {
        return JsonResult.ok(userMapper.selectUser());
    }

    @ApiOperation(value = "删除功能")
    @GetMapping(value = "delete")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
    public JsonResult usersDelete(Long id) {
        if (id<0){
           throw new RuntimeException("运行时异常");
        }
        log.debug("{}", id);
        userMapper.deleteUser(id);
        return JsonResult.ok();
    }

    @ApiImplicitParam(name = "user", value = "用户表", required = true, dataType = "User")
    @ApiOperation(value = "更新功能")
    @PostMapping(value = "update")
    public JsonResult usersUpdate(User user) {
        log.debug("{}", user);
        userMapper.updateUser(user);
        return JsonResult.ok();
    }

    @ApiOperation(value = "用户信息查询")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
    @GetMapping(value = "{id}")
    public JsonResult usersSelectById(@PathVariable Long id) {
        log.debug("{}", id);
        return JsonResult.ok(userMapper.selectById(id));
    }
}
